<?php
namespace app\admin\model;

use think\Db;
use think\Model;

class BusPreOrder extends Model {
	public function searchChannelIdAttr($query, $value, $data) {
		if ($value) {
			$query->where('order.channel_id', $value);
		}
	}
	public function searchCreateTimeAttr($query, $value, $data) {
		$query->where('order.create_time', 'between', [$value, $data['et']]);
	}
	public function searchCountryAttr($query, $value, $data) {
		if ($value) {
			$query->where('phone.country', $value);
		}
	}
	public function searchPhoneAttr($query, $value, $data) {
		if ($value) {
			$query->where('phone.phone', $value);
		}
	}

	public function getStatusAttr($value) {
		$status = [0 => '未发送', 1 => '发送中', 2 => '成功', 3 => '失败'];
		return $status[$value];
	}

	public function getCreateTimeAttr($value) {
		if ($value) {
			return 'GMT+8 ' . $value;
		}
	}

	public function getOrderAll($request) {
		if ($request['phone'] || $request['country']) {
			$data = $this->alias('order')->withSearch(['channel_id', 'create_time', 'country', 'phone'], $request)
				->field('order.*,c.company_name')
				->join('bus_channel c', 'c.channel_id=order.channel_id', 'left')
				->join('bus_pre_order_phone phone', 'order.id=phone.bus_pre_order_id', 'left')
				->where("c.p_id='" . session('relate_id') . "' or c.channel_id='" . session('relate_id') . "'")
			// ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
				->group('order.id')
				->paginate()
				->toArray();
		} else {
			$data = $this->alias('order')->withSearch(['channel_id', 'create_time', 'country', 'phone'], $request)
				->field('order.*,c.company_name')
				->join('bus_channel c', 'c.channel_id=order.channel_id', 'left')
				->where("c.p_id='" . session('relate_id') . "' or c.channel_id='" . session('relate_id') . "'")
			// ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
				->group('order.id')
				->paginate()
				->toArray();
		}
		foreach ($data['data'] as $key => $value) {
			$data['data'][$key]['error_number'] = ((int) $value['phone_numbers'] * (int) $value['sms_numbers']) - (int) $value['success_number'];
		}

		return $data;
	}

	/**
	 * 导出
	 * @创建     lf
	 * @修改
	 * @修改时间   2025-08-28T14:17:35+0800
	 * @描述
	 * @param  [type]                   $request [description]
	 * @return [type]                            [description]
	 */
	public function getOrderPhoneAll($request) {

		$data = $this->alias('order')->withSearch(['channel_id', 'create_time', 'country', 'phone'], $request)
			->field('order.content,phone.create_time,phone.country,phone.msg,phone.status,phone.phone,c.company_name')
			->join('bus_channel c', 'c.channel_id=order.channel_id', 'left')
			->join('bus_pre_order_phone phone', 'order.id=phone.bus_pre_order_id', 'left')
			->where("c.p_id='" . session('relate_id') . "' or c.channel_id='" . session('relate_id') . "'")
			->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
			->select()
			->toArray();

		return $data;
	}
}